/**
 * 
 */
package com.xb.concurrent.hashmap;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author kexue
 *
 */
public class ReadTask implements Runnable {

	private Logger logger = LoggerFactory.getLogger(ReadTask.class);
	private ExecutorService executorService;
	private int cnt ;
	
	public ReadTask( int cnt,ExecutorService executorService){
		this.executorService=executorService;
		this.cnt=cnt;
	}
	public void run() {

		ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(100);
		ConcurrentMap<Character, AtomicInteger> charCountMap = new ConcurrentHashMap<Character, AtomicInteger>();

		String pathname = "C:\\Users\\kexue\\Desktop\\工作\\js库\\框架-前端\\ace\\profile.html";
		BufferedReader reader = null;
		CountDownLatch countDownLatch = new CountDownLatch(cnt);
		  

		for (int i = 0; i < cnt; i++) {
			CharCountTask e = new CharCountTask(charCountMap, queue, countDownLatch);
			executorService.execute(e);
		}

		try {
			reader = new BufferedReader(
					new InputStreamReader(new FileInputStream(new File(pathname)), Charset.defaultCharset()));
			String line;
			try {
				while ((line = reader.readLine()) != null) {
					queue.put(line);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				for(int i=0;i<cnt;i++){
					queue.put("END_TASK");
				}
				 
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		try {
			countDownLatch.await();
			logger.info("countDownLatch completed and return main thread ");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		int index=0;
		for (Character ch : charCountMap.keySet()) {
			System.out.print("index="+(index++)+"\t");
			System.out.print(ch);
			System.out.print(":");
			System.out.println(charCountMap.get(ch));
		}
		
		executorService.shutdown();

		shutdownAndAwaitTermination(executorService);
		
	}
	
	 void shutdownAndAwaitTermination(ExecutorService pool) {
		   pool.shutdown(); // Disable new tasks from being submitted
		   try {
		     // Wait a while for existing tasks to terminate
		     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
		       pool.shutdownNow(); // Cancel currently executing tasks
		       // Wait a while for tasks to respond to being cancelled
		       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
		           System.err.println("Pool did not terminate");
		     }
		   } catch (InterruptedException ie) {
		     // (Re-)Cancel if current thread also interrupted
		     pool.shutdownNow();
		     // Preserve interrupt status
		     Thread.currentThread().interrupt();
		   }
		 }

}
